class_name Map
extends Node2D

@export var bgm:AudioStream

@onready var tileMap :TileMap=$TileMap
@onready var camera:Camera2D=$Player/Camera2D
@onready var player:Player=$Player

func _ready() -> void:
	playBgm()
	getRect()

func playBgm()->void:
	if bgm:Sounds.playBgm(bgm)

# 获取地图的边界
func getRect():
	# 获得图块为单位的矩形宽高
	var mapRect :=tileMap.get_used_rect()
	# 单个图块的像素大小
	# var tileSize:=tileMap.tile_set.tile_size
	var tileSize=tileMap.cell_quadrant_size
	camera.limit_top = mapRect.position.y*tileSize
	camera.limit_left = mapRect.position.x*tileSize
	camera.limit_right = mapRect.end.x*tileSize
	camera.limit_bottom = mapRect.end.y*tileSize

	camera.reset_smoothing()

# 进入地图后的位置
func updatePlayer(pos:Vector2,dir:Player.Direction)->void:
	player.position=pos
	player.fallFrom=pos.y
	player.direction=dir
	camera.reset_smoothing()
	camera.force_update_scroll()

# 场景数据缓存
func toDict()->Dictionary:
	var enemiesAlive:=[]
	for node in getAll('enemies'):
		var path:=get_path_to(node) as String
		enemiesAlive.append(path)

	return {
		enemiesAlive=enemiesAlive
	}

# 场景数据取出
func fromDict(dict:Dictionary)->void:
	for node in getAll('enemies'):
		var path:=get_path_to(node) as String
		if path not in dict.enemiesAlive:
			node.queue_free()

# 获取所有组员
func getAll(obj:String)->Array:
	return get_tree().get_nodes_in_group(obj)
